{% extends "base.html" %}
{% load static %}

{% block title %}标签打印{% endblock %}

{% block extra_css %}
<style>
.print-container {
    max-width: 1200px;
    margin: 0 auto;
}

.template-card {
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    background: white;
    transition: all 0.2s;
    cursor: pointer;
}

.template-card:hover {
    border-color: #007bff;
    box-shadow: 0 2px 8px rgba(0,123,255,0.15);
}

.template-card.selected {
    border-color: #007bff;
    background: #f8f9ff;
}

.template-preview {
    width: 100px;
    height: 60px;
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
}

.asset-selector {
    border: 2px dashed #dee2e6;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    background: #fafafa;
    min-height: 200px;
}

.asset-selector.has-assets {
    border-color: #28a745;
    background: #f8fff9;
}

.selected-asset {
    display: inline-block;
    background: #007bff;
    color: white;
    padding: 5px 10px;
    border-radius: 15px;
    margin: 3px;
    font-size: 0.875rem;
}

.selected-asset .remove-asset {
    margin-left: 5px;
    cursor: pointer;
    opacity: 0.8;
}

.selected-asset .remove-asset:hover {
    opacity: 1;
}

.print-settings {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    margin: 20px 0;
}

.job-status {
    padding: 15px;
    border-radius: 8px;
    margin: 10px 0;
}

.job-status.pending {
    background: #fff3cd;
    border: 1px solid #ffeaa7;
}

.job-status.printing {
    background: #cce5ff;
    border: 1px solid #99d6ff;
}

.job-status.completed {
    background: #d4edda;
    border: 1px solid #c3e6cb;
}

.job-status.failed {
    background: #f8d7da;
    border: 1px solid #f5c6cb;
}

.progress-ring {
    width: 60px;
    height: 60px;
}

.progress-ring-circle {
    stroke: #007bff;
    stroke-width: 4;
    fill: transparent;
    stroke-dasharray: 188.4;
    stroke-dashoffset: 188.4;
    transform: rotate(-90deg);
    transform-origin: 50% 50%;
    transition: stroke-dashoffset 0.3s;
}

.asset-search-modal .modal-body {
    max-height: 500px;
    overflow-y: auto;
}

.asset-item {
    padding: 10px;
    border: 1px solid #dee2e6;
    border-radius: 4px;
    margin: 5px 0;
    cursor: pointer;
    transition: all 0.2s;
}

.asset-item:hover {
    background: #f8f9fa;
    border-color: #007bff;
}

.asset-item.selected {
    background: #007bff;
    color: white;
    border-color: #007bff;
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="print-container">
        <!-- 页面标题 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2><i class="fas fa-print text-primary"></i> 标签打印</h2>
                <p class="text-muted mb-0">Brother PT-9500PC 标签打印机</p>
            </div>
            <div>
                <a href="{% url 'assets:label_template_designer' %}" class="btn btn-outline-primary">
                    <i class="fas fa-plus"></i> 创建模板
                </a>
                <a href="{% url 'assets:label_template_list' %}" class="btn btn-outline-secondary">
                    <i class="fas fa-list"></i> 管理模板
                </a>
            </div>
        </div>

        <div class="row">
            <!-- 左侧：模板选择和设置 -->
            <div class="col-lg-8">
                <!-- 选择模板 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-tags"></i> 选择标签模板</h5>
                    </div>
                    <div class="card-body">
                        {% if templates %}
                        <div class="row">
                            {% for template in templates %}
                            <div class="col-md-6">
                                <div class="template-card" data-template-id="{{ template.id }}" onclick="selectTemplate('{{ template.id }}')">
                                    <div class="d-flex align-items-center">
                                        <div class="template-preview">
                                            <i class="fas fa-tag fa-2x text-muted"></i>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h6 class="mb-1">{{ template.name }}</h6>
                                            <p class="text-muted mb-1 small">{{ template.description|truncatechars:50 }}</p>
                                            <div class="d-flex gap-2">
                                                <span class="badge bg-secondary">{{ template.label_size }}</span>
                                                <span class="badge bg-info">{{ template.fields_config|length }} 字段</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                        {% else %}
                        <div class="text-center py-4">
                            <i class="fas fa-tags fa-3x text-muted mb-3"></i>
                            <h6 class="text-muted">暂无可用模板</h6>
                            <p class="text-muted">请先创建标签模板</p>
                            <a href="{% url 'assets:label_template_designer' %}" class="btn btn-primary">
                                <i class="fas fa-plus"></i> 创建模板
                            </a>
                        </div>
                        {% endif %}
                    </div>
                </div>

                <!-- 选择资产 -->
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fas fa-boxes"></i> 选择要打印的资产</h5>
                        <button class="btn btn-sm btn-primary" onclick="openAssetSelector()">
                            <i class="fas fa-search"></i> 选择资产
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="asset-selector" id="assetSelector">
                            <i class="fas fa-mouse-pointer fa-2x text-muted mb-3"></i>
                            <p class="text-muted mb-0">点击"选择资产"按钮添加要打印标签的资产</p>
                        </div>
                        <div id="selectedAssets" class="mt-3" style="display: none;">
                            <h6>已选择的资产:</h6>
                            <div id="selectedAssetsList"></div>
                        </div>
                    </div>
                </div>

                <!-- 打印设置 -->
                <div class="card mb-4" id="printSettingsCard" style="display: none;">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-cog"></i> 打印设置</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">打印份数</label>
                                    <input type="number" class="form-control" id="printCopies" value="1" min="1" max="10">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">自定义文本</label>
                                    <input type="text" class="form-control" id="customText" placeholder="可选的自定义文本">
                                </div>
                            </div>
                        </div>
                        
                        <div class="d-flex gap-2">
                            <button class="btn btn-success" onclick="startPrinting()" id="printButton">
                                <i class="fas fa-print"></i> 开始打印
                            </button>
                            <button class="btn btn-outline-info" onclick="previewLabels()">
                                <i class="fas fa-eye"></i> 预览标签
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧：打印状态和历史 -->
            <div class="col-lg-4">
                <!-- 当前打印任务 -->
                <div class="card mb-4" id="currentJobCard" style="display: none;">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="fas fa-tasks"></i> 当前打印任务</h6>
                    </div>
                    <div class="card-body">
                        <div id="currentJobStatus"></div>
                    </div>
                </div>

                <!-- 最近的打印任务 -->
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h6 class="mb-0"><i class="fas fa-history"></i> 最近打印</h6>
                        <a href="{% url 'assets:label_print_history' %}" class="btn btn-sm btn-outline-primary">
                            查看全部
                        </a>
                    </div>
                    <div class="card-body">
                        {% if recent_jobs %}
                        <div class="list-group list-group-flush">
                            {% for job in recent_jobs %}
                            <div class="list-group-item border-0 px-0">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="flex-grow-1">
                                        <h6 class="mb-1">{{ job.template.name }}</h6>
                                        <p class="mb-1 text-muted small">
                                            {{ job.total_labels }} 个标签
                                            {% if job.success_rate < 100 %}
                                            (成功率: {{ job.success_rate|floatformat:1 }}%)
                                            {% endif %}
                                        </p>
                                        <small class="text-muted">{{ job.created_at|date:"m-d H:i" }}</small>
                                    </div>
                                    <div class="ms-2">
                                        {% if job.status == 'completed' %}
                                        <span class="badge bg-success">已完成</span>
                                        {% elif job.status == 'printing' %}
                                        <span class="badge bg-primary">打印中</span>
                                        {% elif job.status == 'failed' %}
                                        <span class="badge bg-danger">失败</span>
                                        {% else %}
                                        <span class="badge bg-secondary">{{ job.get_status_display }}</span>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                        {% else %}
                        <div class="text-center py-3">
                            <i class="fas fa-print fa-2x text-muted mb-2"></i>
                            <p class="text-muted mb-0">暂无打印记录</p>
                        </div>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 资产选择模态框 -->
<div class="modal fade asset-search-modal" id="assetSearchModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">选择资产</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <!-- 搜索和筛选 -->
                <div class="row mb-3">
                    <div class="col-md-6">
                        <input type="text" class="form-control" id="assetSearch" placeholder="搜索资产编号或名称">
                    </div>
                    <div class="col-md-3">
                        <select class="form-select" id="categoryFilter">
                            <option value="">全部类别</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <button class="btn btn-primary w-100" onclick="searchAssets()">
                            <i class="fas fa-search"></i> 搜索
                        </button>
                    </div>
                </div>
                
                <!-- 资产列表 -->
                <div id="assetSearchResults">
                    <div class="text-center py-4 text-muted">
                        <i class="fas fa-search fa-2x mb-2"></i>
                        <p>输入关键词搜索资产</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="confirmAssetSelection()">
                    确定选择 (<span id="selectedCount">0</span>)
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 标签预览模态框 -->
<div class="modal fade" id="labelPreviewModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">标签预览</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="labelPreviewContent">
                    <!-- 预览内容将动态加载 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-success" onclick="startPrintingFromPreview()">
                    <i class="fas fa-print"></i> 确认打印
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 全局变量
let selectedTemplateId = null;
let selectedAssets = [];
let tempSelectedAssets = [];
let currentJobId = null;
let jobStatusInterval = null;

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    bindEvents();
});

// 绑定事件
function bindEvents() {
    // 资产搜索
    document.getElementById('assetSearch').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchAssets();
        }
    });
}

// 选择模板
function selectTemplate(templateId) {
    // 移除之前的选择
    document.querySelectorAll('.template-card').forEach(card => {
        card.classList.remove('selected');
    });
    
    // 选择当前模板
    document.querySelector(`[data-template-id="${templateId}"]`).classList.add('selected');
    selectedTemplateId = templateId;
    
    // 显示打印设置
    updatePrintSettings();
}

// 更新打印设置
function updatePrintSettings() {
    const hasTemplate = selectedTemplateId !== null;
    const hasAssets = selectedAssets.length > 0;
    
    if (hasTemplate && hasAssets) {
        document.getElementById('printSettingsCard').style.display = 'block';
    } else {
        document.getElementById('printSettingsCard').style.display = 'none';
    }
}

// 打开资产选择器
function openAssetSelector() {
    tempSelectedAssets = [...selectedAssets];
    new bootstrap.Modal(document.getElementById('assetSearchModal')).show();
    
    // 自动搜索
    setTimeout(() => {
        searchAssets();
    }, 500);
}

// 搜索资产
function searchAssets() {
    const search = document.getElementById('assetSearch').value;
    const category = document.getElementById('categoryFilter').value;
    
    const params = new URLSearchParams({
        search: search,
        category: category
    });
    
    // 显示加载状态
    document.getElementById('assetSearchResults').innerHTML = `
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">搜索中...</span>
            </div>
            <p class="mt-2 text-muted">正在搜索资产...</p>
        </div>
    `;
    
    // 使用后端已注册的资产列表API: assets:asset_list_api -> /assets/api/assets/
    fetch(`{% url 'assets:asset_list_api' %}?${params}`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data && Array.isArray(data.data.assets)) {
                displayAssetResults(data.data.assets);
            } else {
                document.getElementById('assetSearchResults').innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle"></i>
                        ${data.message || '搜索失败'}
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('assetSearchResults').innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    搜索失败
                </div>
            `;
        });
}

// 显示资产搜索结果
function displayAssetResults(assets) {
    const container = document.getElementById('assetSearchResults');
    
    if (assets.length === 0) {
        container.innerHTML = `
            <div class="text-center py-4 text-muted">
                <i class="fas fa-inbox fa-2x mb-2"></i>
                <p>没有找到匹配的资产</p>
            </div>
        `;
        return;
    }
    
    let html = '';
    assets.forEach(asset => {
        const isSelected = tempSelectedAssets.some(a => a.id === asset.id);
        html += `
            <div class="asset-item ${isSelected ? 'selected' : ''}" onclick="toggleAssetSelection(${asset.id}, '${asset.asset_number}', '${asset.name.replace(/'/g, '\\\'')}')">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="mb-1">${asset.asset_number}</h6>
                        <p class="mb-1 text-muted small">${asset.name}</p>
                        <small class="text-muted">${asset.category} | ${asset.department}</small>
                    </div>
                    <div>
                        <span class="badge bg-secondary">${asset.status}</span>
                    </div>
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
    updateSelectedCount();
}

// 切换资产选择
function toggleAssetSelection(assetId, assetNumber, assetName) {
    const index = tempSelectedAssets.findIndex(a => a.id === assetId);
    
    if (index >= 0) {
        // 取消选择
        tempSelectedAssets.splice(index, 1);
    } else {
        // 添加选择
        tempSelectedAssets.push({
            id: assetId,
            asset_number: assetNumber,
            name: assetName
        });
    }
    
    // 更新UI
    const assetItem = document.querySelector(`[onclick*="${assetId}"]`);
    if (assetItem) {
        assetItem.classList.toggle('selected');
    }
    
    updateSelectedCount();
}

// 更新选择计数
function updateSelectedCount() {
    document.getElementById('selectedCount').textContent = tempSelectedAssets.length;
}

// 确认资产选择
function confirmAssetSelection() {
    selectedAssets = [...tempSelectedAssets];
    updateAssetSelector();
    updatePrintSettings();
    
    bootstrap.Modal.getInstance(document.getElementById('assetSearchModal')).hide();
    
    if (selectedAssets.length > 0) {
        showAlert('success', `已选择 ${selectedAssets.length} 个资产`);
    }
}

// 更新资产选择器显示
function updateAssetSelector() {
    const selector = document.getElementById('assetSelector');
    const selectedContainer = document.getElementById('selectedAssets');
    const assetsList = document.getElementById('selectedAssetsList');
    
    if (selectedAssets.length === 0) {
        selector.classList.remove('has-assets');
        selector.innerHTML = `
            <i class="fas fa-mouse-pointer fa-2x text-muted mb-3"></i>
            <p class="text-muted mb-0">点击"选择资产"按钮添加要打印标签的资产</p>
        `;
        selectedContainer.style.display = 'none';
    } else {
        selector.classList.add('has-assets');
        selector.innerHTML = `
            <i class="fas fa-check-circle fa-2x text-success mb-3"></i>
            <p class="text-success mb-0">已选择 ${selectedAssets.length} 个资产</p>
        `;
        
        // 显示已选资产列表
        let assetsHtml = '';
        selectedAssets.forEach(asset => {
            assetsHtml += `
                <span class="selected-asset">
                    ${asset.asset_number}
                    <span class="remove-asset" onclick="removeAsset(${asset.id})">×</span>
                </span>
            `;
        });
        
        assetsList.innerHTML = assetsHtml;
        selectedContainer.style.display = 'block';
    }
}

// 移除资产
function removeAsset(assetId) {
    selectedAssets = selectedAssets.filter(a => a.id !== assetId);
    updateAssetSelector();
    updatePrintSettings();
}

// 预览标签
function previewLabels() {
    if (!selectedTemplateId || selectedAssets.length === 0) {
        showAlert('warning', '请先选择模板和资产');
        return;
    }
    
    const customText = document.getElementById('customText').value;
    
    // 显示预览模态框
    const modal = new bootstrap.Modal(document.getElementById('labelPreviewModal'));
    modal.show();
    
    // 加载预览内容
    document.getElementById('labelPreviewContent').innerHTML = `
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">生成预览...</span>
            </div>
            <p class="mt-2 text-muted">正在生成标签预览...</p>
        </div>
    `;
    
    // 预览第一个资产的标签
    const previewData = {
        template_id: selectedTemplateId,
        asset_id: selectedAssets[0].id,
        custom_data: {
            custom_text: customText
        }
    };
    
    fetch('/assets/labels/preview/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken'),
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(previewData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('labelPreviewContent').innerHTML = `
                <div class="text-center">
                    <h6>标签预览 (${selectedAssets[0].asset_number})</h6>
                    <img src="${data.image_data}" alt="标签预览" class="img-fluid border">
                    <p class="mt-2 text-muted">
                        将为 ${selectedAssets.length} 个资产打印 ${document.getElementById('printCopies').value} 份标签
                    </p>
                </div>
            `;
        } else {
            document.getElementById('labelPreviewContent').innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    ${data.message || '预览生成失败'}
                </div>
            `;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        document.getElementById('labelPreviewContent').innerHTML = `
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i>
                预览生成失败
            </div>
        `;
    });
}

// 开始打印
function startPrinting() {
    if (!selectedTemplateId || selectedAssets.length === 0) {
        showAlert('warning', '请先选择模板和资产');
        return;
    }
    
    const printData = {
        template_id: selectedTemplateId,
        asset_ids: selectedAssets.map(a => a.id),
        copies: parseInt(document.getElementById('printCopies').value),
        print_settings: {
            custom_text: document.getElementById('customText').value
        }
    };
    
    // 禁用打印按钮
    const printButton = document.getElementById('printButton');
    printButton.disabled = true;
    printButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 创建打印任务...';
    
    // 使用后端路由: assets:create_print_job -> /assets/label-print/create-job/
    fetch("{% url 'assets:create_print_job' %}", {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken'),
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(printData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            currentJobId = data.job_id;
            showCurrentJob();
            startJobStatusPolling();
            showAlert('success', '打印任务已创建');
        } else {
            showAlert('danger', data.message || '创建打印任务失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('danger', '创建打印任务失败');
    })
    .finally(() => {
        // 恢复打印按钮
        printButton.disabled = false;
        printButton.innerHTML = '<i class="fas fa-print"></i> 开始打印';
    });
}

// 从预览开始打印
function startPrintingFromPreview() {
    bootstrap.Modal.getInstance(document.getElementById('labelPreviewModal')).hide();
    startPrinting();
}

// 显示当前任务
function showCurrentJob() {
    document.getElementById('currentJobCard').style.display = 'block';
}

// 开始任务状态轮询
function startJobStatusPolling() {
    if (jobStatusInterval) {
        clearInterval(jobStatusInterval);
    }
    
    jobStatusInterval = setInterval(() => {
        if (currentJobId) {
            updateJobStatus();
        }
    }, 2000);
}

// 更新任务状态
function updateJobStatus() {
    // 使用后端路由: assets:print_job_status -> /assets/label-print/job-status/<job_id>/
    fetch(buildPrintJobStatusUrl(currentJobId))
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayJobStatus(data.job);
                
                // 如果任务完成，停止轮询
                if (['completed', 'failed', 'cancelled'].includes(data.job.status)) {
                    clearInterval(jobStatusInterval);
                    jobStatusInterval = null;
                }
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
}

// 显示任务状态
function displayJobStatus(job) {
    const container = document.getElementById('currentJobStatus');
    
    let statusClass = 'pending';
    let statusIcon = 'fas fa-clock';
    let statusText = '等待中';
    
    switch (job.status) {
        case 'printing':
            statusClass = 'printing';
            statusIcon = 'fas fa-print';
            statusText = '打印中';
            break;
        case 'completed':
            statusClass = 'completed';
            statusIcon = 'fas fa-check-circle';
            statusText = '已完成';
            break;
        case 'failed':
            statusClass = 'failed';
            statusIcon = 'fas fa-exclamation-circle';
            statusText = '失败';
            break;
    }
    
    const progress = job.total_labels > 0 ? (job.printed_labels / job.total_labels * 100) : 0;
    
    container.innerHTML = `
        <div class="job-status ${statusClass}">
            <div class="d-flex align-items-center">
                <div class="me-3">
                    <i class="${statusIcon} fa-2x"></i>
                </div>
                <div class="flex-grow-1">
                    <h6 class="mb-1">${statusText}</h6>
                    <div class="progress mb-2" style="height: 6px;">
                        <div class="progress-bar" role="progressbar" style="width: ${progress}%"></div>
                    </div>
                    <small>
                        ${job.printed_labels} / ${job.total_labels} 标签
                        ${job.success_rate ? `(成功率: ${job.success_rate.toFixed(1)}%)` : ''}
                    </small>
                </div>
            </div>
            ${job.error_message ? `<div class="mt-2 text-danger small">${job.error_message}</div>` : ''}
        </div>
    `;
}

// 工具函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function showAlert(type, message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

// 构建打印任务状态查询URL
function buildPrintJobStatusUrl(jobId) {
    const tpl = "{% url 'assets:print_job_status' 0 %}";
    // 例如: /assets/label-print/job-status/0/ -> /assets/label-print/job-status/<jobId>/
    return tpl.replace('/0/', `/${jobId}/`);
}
</script>
{% endblock %}